﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

namespace AUV5.Web.Handler
{
    /// <summary>
    /// MathValidateCodeHandler 的摘要说明
    /// </summary>
    public class MathValidateCodeHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext hc)
        {
            hc.Response.ContentType = "image/gif";

            Random r = new Random();
            string finnal = "";

            bool create = true;
            do
            {
                int first = r.Next(0, 10);
                int second = r.Next(0, 10);
                int flag = r.Next(0, 2);
                string mark = "";

                if (flag == 0)
                {
                    mark = "+";
                    create = false;
                    finnal = first.ToString() + mark + second.ToString() + "=?";
                    hc.Session["MathIdentifyResult"] = first + second;
                }
                else
                {
                    mark = "-";
                    if (first > second)
                    {
                        create = false;
                        finnal = first.ToString() + mark + second.ToString() + "=?";
                        hc.Session["MathIdentifyResult"] = first - second;
                    }
                }
            } while (create);

            int lengthStr = finnal.Length;
            int widthCode = lengthStr * 50;

            Bitmap b = new Bitmap(widthCode, 60);
            Graphics g = Graphics.FromImage(b);

            g.FillRectangle(new SolidBrush(Color.White), 0, 0, widthCode, 60);

            Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
            for (int i = 0; i < lengthStr; i++)
            {
                 Color c = System.Drawing.ColorTranslator.FromHtml("#0192B5");
                g.DrawString(finnal.Substring(i, 1), font, new SolidBrush(c), i * 50, r.Next(0, 10));
            }
            
            b.Save(hc.Response.OutputStream, ImageFormat.Gif);

            hc.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}